<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩管理 - 教学管理系统</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid #3c5166;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .user-info {
            margin-top: 10px;
            font-size: 14px;
            opacity: 0.8;
        }

        .menu {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .menu li:hover {
            background-color: #3c5166;
        }

        .menu li.active {
            background-color: #3498db;
        }

        .menu a {
            color: white;
            text-decoration: none;
            display: block;
        }

        .content {
            flex: 1;
            padding: 20px;
        }

        .content-header {
            margin-bottom: 30px;
        }

        .content-header h1 {
            margin: 0;
            color: #333;
            font-size: 24px;
        }

        .filter-controls {
            display: flex;
            margin-bottom: 20px;
            gap: 15px;
        }

        .filter-control {
            flex: 1;
        }

        .filter-control label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #555;
        }

        .filter-control select,
        .filter-control input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .search-box {
            margin-bottom: 20px;
        }

        .search-box input {
            width: 300px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .search-box button {
            padding: 8px 16px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 8px;
        }

        .grades-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        table th,
        table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        table th {
            background-color: #f8f9fa;
            color: #333;
            font-weight: 600;
        }

        table tr:hover {
            background-color: #f5f5f5;
        }

        .grade-input {
            width: 60px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-align: center;
        }

        .btn {
            display: inline-block;
            padding: 6px 12px;
            background-color: #3498db;
            color: white;
            border-radius: 4px;
            text-decoration: none;
            font-size: 14px;
            border: none;
            cursor: pointer;
        }

        .btn:hover {
            background-color: #2980b9;
        }

        .btn.save {
            background-color: #27ae60;
        }

        .btn.save:hover {
            background-color: #219955;
        }

        .status-icon {
            width: 16px;
            height: 16px;
            display: inline-block;
            border-radius: 50%;
            margin-right: 5px;
            vertical-align: middle;
        }

        .status-icon.saved {
            background-color: #27ae60;
        }

        .status-icon.unsaved {
            background-color: #e74c3c;
        }

        .logout {
            margin-top: auto;
            padding: 20px;
        }

        .logout a {
            color: #e74c3c;
            text-decoration: none;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>教学管理系统</h2>
                <div class="user-info" th:if="${session.user}">
                    <span th:text="${session.user.username}">teacher1</span> - 教师
                </div>
            </div>
            <ul class="menu">
                <li><a href="/teacher/dashboard">我的概览</a></li>
                <li><a href="/teacher/courses">我的课程</a></li>
                <li><a href="/teacher/students">我的学生</a></li>
                <li class="active"><a href="/teacher/grades">成绩管理</a></li>
                <li><a href="/teacher/profile">个人信息</a></li>
            </ul>
            <div class="logout">
                <a href="/logout">退出登录</a>
            </div>
        </div>

        <div class="content">
            <div class="content-header">
                <h1>成绩管理</h1>
            </div>

            <div class="filter-controls">
                <div class="filter-control">
                    <label for="courseFilter">选择课程</label>
                    <select id="courseFilter" onchange="filterGrades()">
                        <option value="">全部课程</option>
                        <option th:each="course : ${courses}" th:value="${course.courseId}"
                            th:text="${course.name + ' (' + course.courseId + ')'}">计算机导论 (CS101)</option>
                    </select>
                </div>
                <div class="filter-control">
                    <label for="gradeTypeFilter">成绩类型</label>
                    <select id="gradeTypeFilter" onchange="filterGrades()">
                        <option value="">全部类型</option>
                        <option value="midterm">期中考试</option>
                        <option value="final">期末考试</option>
                        <option value="assignment">作业</option>
                        <option value="project">项目</option>
                        <option value="quiz">测验</option>
                    </select>
                </div>
                <div class="filter-control">
                    <label for="statusFilter">录入状态</label>
                    <select id="statusFilter" onchange="filterGrades()">
                        <option value="">全部状态</option>
                        <option value="entered">已录入</option>
                        <option value="missing">未录入</option>
                    </select>
                </div>
            </div>

            <div class="search-box">
                <input type="text" id="searchInput" placeholder="搜索学生姓名或学号">
                <button onclick="searchGrades()">搜索</button>
            </div>

            <div class="grades-container">
                <table>
                    <thead>
                        <tr>
                            <th>学号</th>
                            <th>姓名</th>
                            <th>课程</th>
                            <th>类型</th>
                            <th>分数</th>
                            <th>满分</th>
                            <th>占比</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="gradesTable">
                        <tr th:if="${grades == null || grades.isEmpty()}">
                            <td colspan="9" style="text-align: center;">暂无成绩数据</td>
                        </tr>
                        <tr th:each="grade : ${grades}"
                            th:attr="data-course-id=${grade.courseId}, data-grade-type=${grade.type}, data-status=${grade.score != null ? 'entered' : 'missing'}">
                            <td th:text="${grade.studentId}">20230001</td>
                            <td th:text="${grade.studentName}">张三</td>
                            <td th:text="${grade.courseName}">计算机导论</td>
                            <td th:text="${grade.typeDesc}">期末考试</td>
                            <td>
                                <input type="number" class="grade-input" th:id="'grade-' + ${grade.id}"
                                    th:value="${grade.score}" min="0" th:max="${grade.maxScore}"
                                    onchange="markUnsaved(this)" />
                            </td>
                            <td th:text="${grade.maxScore}">100</td>
                            <td th:text="${grade.weight + '%'}">40%</td>
                            <td>
                                <span th:if="${grade.score != null}" class="status-icon saved" title="已保存"></span>
                                <span th:if="${grade.score == null}" class="status-icon unsaved" title="未保存"></span>
                                <span th:text="${grade.score != null ? '已录入' : '未录入'}">已录入</span>
                            </td>
                            <td>
                                <button class="btn save" th:onclick="'saveGrade(' + ${grade.id} + ')'">保存</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            console.log('教师成绩管理页面加载完成');
        });

        // 标记未保存状态
        function markUnsaved(input) {
            const row = input.closest('tr');
            const statusCell = row.cells[7];
            statusCell.innerHTML = '<span class="status-icon unsaved" title="未保存"></span>未保存';
            row.setAttribute('data-status', 'unsaved');
        }

        // 保存成绩
        function saveGrade(gradeId) {
            const input = document.getElementById('grade-' + gradeId);
            const score = input.value;

            if (score === '') {
                alert('请输入有效分数');
                return;
            }

            console.log('保存成绩:', gradeId, '分数:', score);

            // 显示保存中状态
            const row = input.closest('tr');
            const buttonCell = row.cells[8];
            const originalButton = buttonCell.innerHTML;
            buttonCell.innerHTML = '<button class="btn" disabled>保存中...</button>';

            // 发送请求到后端保存成绩
            fetch('/teacher/grade/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    gradeId: gradeId,
                    score: score
                }),
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('保存失败');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('成绩保存成功:', data);

                    // 更新状态为已保存
                    const statusCell = row.cells[7];
                    statusCell.innerHTML = '<span class="status-icon saved" title="已保存"></span>已录入';
                    row.setAttribute('data-status', 'entered');

                    // 恢复按钮
                    buttonCell.innerHTML = originalButton;
                })
                .catch(error => {
                    console.error('保存成绩失败:', error);
                    alert('保存失败: ' + error.message);

                    // 恢复按钮
                    buttonCell.innerHTML = originalButton;
                });
        }

        // 筛选成绩
        function filterGrades() {
            searchGrades();
        }

        // 搜索成绩
        function searchGrades() {
            const searchTerm = document.getElementById('searchInput').value.trim().toLowerCase();
            const courseFilter = document.getElementById('courseFilter').value;
            const gradeTypeFilter = document.getElementById('gradeTypeFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;

            console.log('搜索成绩:', searchTerm, '课程:', courseFilter, '类型:', gradeTypeFilter, '状态:', statusFilter);

            const rows = document.querySelectorAll('#gradesTable tr:not(:first-child)');
            let matchCount = 0;

            rows.forEach(row => {
                if (!row.cells || row.cells.length < 2) return;

                const studentId = row.cells[0].textContent.toLowerCase();
                const studentName = row.cells[1].textContent.toLowerCase();
                const courseId = row.getAttribute('data-course-id');
                const gradeType = row.getAttribute('data-grade-type');
                const status = row.getAttribute('data-status');

                const matchesCourse = courseFilter === '' || courseFilter === courseId;
                const matchesType = gradeTypeFilter === '' || gradeTypeFilter === gradeType;
                const matchesStatus = statusFilter === '' || statusFilter === status;
                const matchesSearch = studentId.includes(searchTerm) ||
                    studentName.includes(searchTerm) ||
                    searchTerm === '';

                if (matchesCourse && matchesType && matchesStatus && matchesSearch) {
                    row.style.display = '';
                    matchCount++;
                } else {
                    row.style.display = 'none';
                }
            });

            // 显示搜索结果为空的提示
            const emptyRow = document.querySelector('#gradesTable tr:first-child');
            if (emptyRow && emptyRow.cells[0].getAttribute('colspan')) {
                if (matchCount === 0 && rows.length > 0) {
                    emptyRow.style.display = '';
                    emptyRow.cells[0].textContent = '未找到匹配的成绩记录';
                } else {
                    emptyRow.style.display = rows.length === 0 ? '' : 'none';
                }
            }
        }
    </script>
</body>

</html>